<template>
    <div>
        <page-header title="第二步" content="设置展示表格" style="margin-bottom: 0;"/>

        <el-row>
            <el-col :span="backUpStatus?7:1">
                <page-main style="margin-right: 0;">
                    <i v-bind:class="backUpStatus?backUp:backDown" v-on:click="backUpStatus=(backUpStatus?false:true)"
                       style="cursor: pointer; margin-left: -6px;"></i>
                    <el-form v-if="backUpStatus">
                        <el-form-item label="选择区块">
                            <el-select v-model="check_block" placeholder="请选择表单">
                                <el-option label="区域一" value="shanghai"></el-option>
                                <el-option label="区域二" value="beijing"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <form-create v-if="backUpStatus"
                                 v-model="fapi"
                                 :rule="rule"
                                 :option="option"
                                 @submit="onSubmit"
                    ></form-create>
                    <codemirror v-model="code" :options="cmOption" v-if="backUpStatus"/>
                </page-main>
            </el-col>
            <el-col :span="backUpStatus?17:23">
                <page-main title="演示">
                    <ele-table
                        :columns-desc="columnsDesc"
                        :delete-fn="handleDelete"
                        :deletes-fn="handleDeletes"
                        :is-show-index="false"
                        :is-show-right-delete="true"
                        :is-show-top-delete="true"
                        :request-fn="handleRequest"
                        :right-buttons="rightButtons"
                        :top-buttons="topButtons"
                        :top-search="topSearch"
                        :top-time="topTime"
                        :update-fn="handleUpdate"
                        ref="table"
                    ></ele-table>
                </page-main>
            </el-col>
        </el-row>
        <fixed-action-bar style="z-index: 100;">
            <el-button type="primary" @click="onSubmit">下一步，选择表格</el-button>
        </fixed-action-bar>
    </div>
</template>

<script>
// language
import 'codemirror/mode/javascript/javascript.js'
// theme css
import 'codemirror/theme/monokai.css'
// require active-line.js
import 'codemirror/addon/selection/active-line.js'
// styleSelectedText
import 'codemirror/addon/selection/mark-selection.js'
import 'codemirror/addon/search/searchcursor.js'
// hint
import 'codemirror/addon/hint/show-hint.js'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/javascript-hint.js'
import 'codemirror/addon/selection/active-line.js'
// highlightSelectionMatches
import 'codemirror/addon/scroll/annotatescrollbar.js'
import 'codemirror/addon/search/matchesonscrollbar.js'
import 'codemirror/addon/search/searchcursor.js'
import 'codemirror/addon/search/match-highlighter.js'
// keyMap
import 'codemirror/mode/clike/clike.js'
import 'codemirror/addon/edit/matchbrackets.js'
import 'codemirror/addon/comment/comment.js'
import 'codemirror/addon/dialog/dialog.js'
import 'codemirror/addon/dialog/dialog.css'
import 'codemirror/addon/search/searchcursor.js'
import 'codemirror/addon/search/search.js'
import 'codemirror/keymap/sublime.js'
// foldGutter
import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/brace-fold.js'
import 'codemirror/addon/fold/comment-fold.js'
import 'codemirror/addon/fold/foldcode.js'
import 'codemirror/addon/fold/foldgutter.js'
import 'codemirror/addon/fold/indent-fold.js'
import 'codemirror/addon/fold/markdown-fold.js'
import 'codemirror/addon/fold/xml-fold.js'

export default {
    name: "new_page_table",
    data() {
        return {
            backUp: 'el-icon-s-fold',
            backDown: 'el-icon-s-unfold',
            backUpStatus: true,
            code: 'const A = 10',
            cmOption: {
                tabSize: 4,
                styleActiveLine: false,
                lineNumbers: true,
                styleSelectedText: false,
                line: true,
                foldGutter: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: true},
                mode: 'text/javascript',
                // hint.js options
                hintOptions: {
                    completeSingle: false
                },
                keyMap: "sublime",
                matchBrackets: true,
                showCursorWhenSelecting: true,
                theme: "monokai",
                extraKeys: {"Ctrl": "autocomplete"}
            },
            fapi: null,
            check_block: '',
            rule: formCreate.parseJson('[{"type":"input","field":"api_url","title":"接口地址","info":"","_fc_drag_tag":"input","hidden":false,"display":true}]'),
            option: formCreate.parseJson('{"form":{"labelPosition":"left","size":"medium","labelWidth":"125px","hideRequiredAsterisk":false,"showMessage":true,"inlineMessage":false},"submitBtn":false}'),

            mockData: [],
            rightButtons: [
                {
                    text: '编辑',
                    click: (id, index, data) => {
                        console.log(id, index, data)
                        this.$message({
                            type: 'success',
                            message: '点击编辑了!'
                        })
                    }
                }
            ],
            topButtons: [
                {
                    text: '新增',
                    click: (data) => {
                        console.log(data)
                        this.$message({
                            type: 'success',
                            message: '点击新增!'
                        })
                    }
                },
                {
                    text: '启用',
                    attrs: {
                        type: 'success'
                    },
                    click: (ids) => {
                        console.log(ids)
                        if (ids.length === 0) return
                        this.$refs.table.reset()
                        this.$message({
                            type: 'success',
                            message: '更新成功!'
                        })
                        setTimeout(() => {
                            this.mockData = this.mockData.map((item) => {
                                if (ids.indexOf(item.id) > -1) {
                                    item.status = 1
                                }
                                return item
                            })
                        }, 1000)
                    }
                },
                {
                    text: '禁用',
                    attrs: {
                        type: 'warning'
                    },
                    click: (ids) => {
                        console.log(ids)
                        if (ids.length === 0) return
                        this.$refs.table.reset()
                        this.$message({
                            type: 'success',
                            message: '更新成功!'
                        })
                        setTimeout(() => {
                            this.mockData = this.mockData.map((item) => {
                                if (ids.indexOf(item.id) > -1) {
                                    item.status = 0
                                }
                                return item
                            })
                        }, 1000)
                    }
                }
            ],
            topTime: 'create_time',
            topSearch: [
                {text: '用户名', value: 'name'}, {text: '省份', value: 'address'}
            ],
            columnsDesc: {
                id: {
                    text: 'ID',
                    sortable: true,
                    width: 80
                },
                avatar: {
                    text: '头像',
                    type: 'image'
                },
                name: {
                    text: '名字',
                    type: 'input'
                },
                type: {
                    text: '类型',
                    options: ['VIP1', 'VIP2', 'VIP3', 'SVIP']
                },
                address: {
                    text: '省份'
                },
                birthday: {
                    toggleShow: true,
                    text: '出生日期'
                },
                status: {
                    text: '状态',
                    type: 'status',
                    toggleShow: true,
                    width: 100,
                    options: [
                        {text: '正常', type: 'success', value: 1},
                        {text: '禁用', type: 'danger', value: 0}
                    ]
                },
                create_time: {
                    text: '创建时间',
                    type: 'datetime-text'
                }
            }
        }
    },
    methods: {
        onSubmit() {
        },
        handleRequest(params) {
            console.log(params)
            return new Promise((resolve) => {
                setTimeout(() => {
                    let list = this.mockData
                    // 过滤
                    if (params._filter) {
                        const filters = params._filter.split('|')
                        filters.forEach((item) => {
                            item = item.split(':')
                            const field = item[0]
                            const values = item[1].split(',')
                            list = list.filter((item) => {
                                // eslint-disable-next-line eqeqeq
                                return values.some((value) => value == item[field])
                            })
                        })
                    }

                    // 时间过滤
                    if (params._filter_time) {
                        const filterTimes = params._filter_time.split('|')
                        filterTimes.forEach((item) => {
                            item = item.split(':')
                            const field = item[0]
                            const [startTime, endTime] = item[1].split(',')
                            list = list.filter((item) => {
                                return item[field] > Number(startTime) && item[field] <= Number(endTime)
                            })
                        })
                    }

                    // 搜索过滤
                    if (params._search_field && params._search_keyword) {
                        const searchFields = params._search_field.split('|')
                        list = list.filter((item) => {
                            return searchFields.some(field => {
                                return item[field].indexOf(params._search_keyword) > -1
                            })
                        })
                    }

                    // 排序
                    if (params._order_field) {
                        list.sort((a, b) => {
                            return params._order_direction === 'asc' ? a[params._order_field] - b[params._order_field] : b[params._order_field] - a[params._order_field]
                        })
                    }

                    // 截取
                    resolve({
                        total: list.length,
                        list: list.slice((params.page - 1) * params.size, params.page * params.size)
                    })
                }, 1000)
            })
        },
        handleDelete(primaryKey, index, row) {
            console.log(primaryKey, index, row)
            this.mockData = this.mockData.filter((item) => item.id !== primaryKey)
            return Promise.resolve()
        },
        handleDeletes(ids, data) {
            console.log(ids, data)
            this.mockData = this.mockData.filter((item) => ids.indexOf(item.id) === -1)
            return Promise.resolve()
        },
        handleUpdate(data) {
            console.log(data)
            this.mockData = this.mockData.map((item) => {
                if (item.id === data.id) {
                    item = Object.assign({}, item, data)
                }
                return item
            })
            return Promise.resolve()
        },
        // 测试数据
        getMockData() {
            const data = Mock.mock({
                // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
                'list|40': [{
                    // 属性 id 是一个自增数，起始值为 1，每次增 1
                    'id|+1': 1,
                    'name': '@cname',
                    'birthday': '@datetime',
                    'address': '@province',
                    'type|1': [
                        'VIP1',
                        'VIP2',
                        'VIP3',
                        'SVIP'
                    ],
                    'avatar': function () {
                        return Random.image('250x250', Mock.mock('@hex'))
                    },
                    'create_time': function () {
                        return (new Date().getTime() / 1000) - Random.integer(0, 864000)
                    },
                    'status|0-1': 1
                }]
            })
            return data.list
        }
    },
    mounted() {
        const data = this.getMockData()
        this.mockData = data
    }
}
</script>
<style>
.CodeMirror-focused .cm-matchhighlight {
    background-image: url();
    background-position: bottom;
    background-repeat: repeat-x;
}
.CodeMirror {
    height: auto;
    min-height: 300px;
    margin-bottom: 20px;
}
</style>
